<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" />
        <link href="./assets/ffd55088/css/bootstrap.css" rel="stylesheet">
<link href="./assets/5cf9384a/solarized_light.css" rel="stylesheet">
<link href="./assets/6c54116e/style.css" rel="stylesheet">
<script src="./assets/a44cef0f/jquery.js"></script>
<script src="./assets/ffd55088/js/bootstrap.js"></script>
<script src="./assets/8ac4e28a/jssearch.js"></script>    <title>Data Caching - Caching - The Definitive Guide to Yii 2.0</title>
</head>
<body>

<div class="wrap">
    <nav id="w1669" class="navbar-inverse navbar-fixed-top navbar" role="navigation"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w1669-collapse"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span></button><a class="navbar-brand" href="./index.html">The Definitive Guide to Yii 2.0</a></div><div id="w1669-collapse" class="collapse navbar-collapse"><ul id="w1670" class="navbar-nav nav"><li><a href="./index.html">Class reference</a></li>
<li class="dropdown"><a class="dropdown-toggle" href="#" data-toggle="dropdown">Extensions <b class="caret"></b></a><ul id="w1671" class="dropdown-menu"><li><a href="./ext-apidoc-index.html" tabindex="-1">apidoc</a></li>
<li><a href="./ext-authclient-index.html" tabindex="-1">authclient</a></li>
<li><a href="./ext-bootstrap-index.html" tabindex="-1">bootstrap</a></li>
<li><a href="./ext-codeception-index.html" tabindex="-1">codeception</a></li>
<li><a href="./ext-debug-index.html" tabindex="-1">debug</a></li>
<li><a href="./ext-elasticsearch-index.html" tabindex="-1">elasticsearch</a></li>
<li><a href="./ext-faker-index.html" tabindex="-1">faker</a></li>
<li><a href="./ext-gii-index.html" tabindex="-1">gii</a></li>
<li><a href="./ext-imagine-index.html" tabindex="-1">imagine</a></li>
<li><a href="./ext-jui-index.html" tabindex="-1">jui</a></li>
<li><a href="./ext-mongodb-index.html" tabindex="-1">mongodb</a></li>
<li><a href="./ext-redis-index.html" tabindex="-1">redis</a></li>
<li><a href="./ext-smarty-index.html" tabindex="-1">smarty</a></li>
<li><a href="./ext-sphinx-index.html" tabindex="-1">sphinx</a></li>
<li><a href="./ext-swiftmailer-index.html" tabindex="-1">swiftmailer</a></li>
<li><a href="./ext-twig-index.html" tabindex="-1">twig</a></li></ul></li>
<li><a href="./guide-README.html">Guide</a></li></ul><div class="navbar-form navbar-left" role="search">
  <div class="form-group">
    <input id="searchbox" type="text" class="form-control" placeholder="Search">
  </div>
</div>
</div></nav>
    <div id="search-resultbox" style="display: none;" class="modal-content">
        <ul id="search-results">
        </ul>
    </div>

    
<div class="row">
    <div class="col-md-2">
                <div id="navigation" class="list-group"><a class="list-group-item" href="#navigation-1653" data-toggle="collapse" data-parent="#navigation">Introduction <b class="caret"></b></a><div id="navigation-1653" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-intro-yii.html">About Yii</a>
<a class="list-group-item" href="./guide-intro-upgrade-from-v1.html">Upgrading from Version 1.1</a></div>
<a class="list-group-item" href="#navigation-1654" data-toggle="collapse" data-parent="#navigation">Getting Started <b class="caret"></b></a><div id="navigation-1654" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-start-installation.html">Installing Yii</a>
<a class="list-group-item" href="./guide-start-workflow.html">Running Applications</a>
<a class="list-group-item" href="./guide-start-hello.html">Saying Hello</a>
<a class="list-group-item" href="./guide-start-forms.html">Working with Forms</a>
<a class="list-group-item" href="./guide-start-databases.html">Working with Databases</a>
<a class="list-group-item" href="./guide-start-gii.html">Generating Code with Gii</a>
<a class="list-group-item" href="./guide-start-looking-ahead.html">Looking Ahead</a></div>
<a class="list-group-item" href="#navigation-1655" data-toggle="collapse" data-parent="#navigation">Application Structure <b class="caret"></b></a><div id="navigation-1655" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-structure-overview.html">Overview</a>
<a class="list-group-item" href="./guide-structure-entry-scripts.html">Entry Scripts</a>
<a class="list-group-item" href="./guide-structure-applications.html">Applications</a>
<a class="list-group-item" href="./guide-structure-application-components.html">Application Components</a>
<a class="list-group-item" href="./guide-structure-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-structure-models.html">Models</a>
<a class="list-group-item" href="./guide-structure-views.html">Views</a>
<a class="list-group-item" href="./guide-structure-modules.html">Modules</a>
<a class="list-group-item" href="./guide-structure-filters.html">Filters</a>
<a class="list-group-item" href="./guide-structure-widgets.html">Widgets</a>
<a class="list-group-item" href="./guide-structure-assets.html">Assets</a>
<a class="list-group-item" href="./guide-structure-extensions.html">Extensions</a></div>
<a class="list-group-item" href="#navigation-1656" data-toggle="collapse" data-parent="#navigation">Handling Requests <b class="caret"></b></a><div id="navigation-1656" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-runtime-overview.html">Overview</a>
<a class="list-group-item" href="./guide-runtime-bootstrapping.html">Bootstrapping</a>
<a class="list-group-item" href="./guide-runtime-routing.html">Routing and URL Creation</a>
<a class="list-group-item" href="./guide-runtime-requests.html">Requests</a>
<a class="list-group-item" href="./guide-runtime-responses.html">Responses</a>
<a class="list-group-item" href="./guide-runtime-sessions-cookies.html">Sessions and Cookies</a>
<a class="list-group-item" href="./guide-runtime-handling-errors.html">Handling Errors</a>
<a class="list-group-item" href="./guide-runtime-logging.html">Logging</a></div>
<a class="list-group-item" href="#navigation-1657" data-toggle="collapse" data-parent="#navigation">Key Concepts <b class="caret"></b></a><div id="navigation-1657" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-concept-components.html">Components</a>
<a class="list-group-item" href="./guide-concept-properties.html">Properties</a>
<a class="list-group-item" href="./guide-concept-events.html">Events</a>
<a class="list-group-item" href="./guide-concept-behaviors.html">Behaviors</a>
<a class="list-group-item" href="./guide-concept-configurations.html">Configurations</a>
<a class="list-group-item" href="./guide-concept-aliases.html">Aliases</a>
<a class="list-group-item" href="./guide-concept-autoloading.html">Class Autoloading</a>
<a class="list-group-item" href="./guide-concept-service-locator.html">Service Locator</a>
<a class="list-group-item" href="./guide-concept-di-container.html">Dependency Injection Container</a></div>
<a class="list-group-item" href="#navigation-1658" data-toggle="collapse" data-parent="#navigation">Working with Databases <b class="caret"></b></a><div id="navigation-1658" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-db-dao.html">Data Access Objects</a>
<a class="list-group-item" href="./guide-db-query-builder.html">Query Builder</a>
<a class="list-group-item" href="./guide-db-active-record.html">Active Record</a>
<a class="list-group-item" href="./guide-db-migrations.html">Migrations</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-sphinx/blob/master/docs/guide/README.md">Sphinx</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-redis/blob/master/docs/guide/README.md">Redis</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-mongodb/blob/master/docs/guide/README.md">MongoDB</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/README.md">ElasticSearch</a></div>
<a class="list-group-item" href="#navigation-1659" data-toggle="collapse" data-parent="#navigation">Getting Data from Users <b class="caret"></b></a><div id="navigation-1659" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-input-forms.html">Creating Forms</a>
<a class="list-group-item" href="./guide-input-validation.html">Validating Input</a>
<a class="list-group-item" href="./guide-input-file-upload.html">Uploading Files</a>
<a class="list-group-item" href="./guide-input-tabular-input.html">Collecting Tabular Input</a>
<a class="list-group-item" href="./guide-input-multiple-models.html">Getting Data for Multiple Models</a></div>
<a class="list-group-item" href="#navigation-1660" data-toggle="collapse" data-parent="#navigation">Displaying Data <b class="caret"></b></a><div id="navigation-1660" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-output-formatting.html">Data Formatting</a>
<a class="list-group-item" href="./guide-output-pagination.html">Pagination</a>
<a class="list-group-item" href="./guide-output-sorting.html">Sorting</a>
<a class="list-group-item" href="./guide-output-data-providers.html">Data Providers</a>
<a class="list-group-item" href="./guide-output-data-widgets.html">Data Widgets</a>
<a class="list-group-item" href="./guide-output-client-scripts.html">Working with Client Scripts</a>
<a class="list-group-item" href="./guide-output-theming.html">Theming</a></div>
<a class="list-group-item" href="#navigation-1661" data-toggle="collapse" data-parent="#navigation">Security <b class="caret"></b></a><div id="navigation-1661" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-security-overview.html">Overview</a>
<a class="list-group-item" href="./guide-security-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-security-authorization.html">Authorization</a>
<a class="list-group-item" href="./guide-security-passwords.html">Working with Passwords</a>
<a class="list-group-item" href="./guide-security-cryptography.html">Cryptography</a>
<a class="list-group-item" href="./guide-structure-views.html#security">Views security</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-authclient/blob/master/docs/guide/README.md">Auth Clients</a>
<a class="list-group-item" href="./guide-security-best-practices.html">Best Practices</a></div>
<a class="list-group-item active" href="#navigation-1662" data-toggle="collapse" data-parent="#navigation">Caching <b class="caret"></b></a><div id="navigation-1662" class="submenu panel-collapse collapse in"><a class="list-group-item" href="./guide-caching-overview.html">Overview</a>
<a class="list-group-item active" href="./guide-caching-data.html">Data Caching</a>
<a class="list-group-item" href="./guide-caching-fragment.html">Fragment Caching</a>
<a class="list-group-item" href="./guide-caching-page.html">Page Caching</a>
<a class="list-group-item" href="./guide-caching-http.html">HTTP Caching</a></div>
<a class="list-group-item" href="#navigation-1663" data-toggle="collapse" data-parent="#navigation">RESTful Web Services <b class="caret"></b></a><div id="navigation-1663" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-rest-quick-start.html">Quick Start</a>
<a class="list-group-item" href="./guide-rest-resources.html">Resources</a>
<a class="list-group-item" href="./guide-rest-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-rest-routing.html">Routing</a>
<a class="list-group-item" href="./guide-rest-response-formatting.html">Response Formatting</a>
<a class="list-group-item" href="./guide-rest-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-rest-rate-limiting.html">Rate Limiting</a>
<a class="list-group-item" href="./guide-rest-versioning.html">Versioning</a>
<a class="list-group-item" href="./guide-rest-error-handling.html">Error Handling</a></div>
<a class="list-group-item" href="#navigation-1664" data-toggle="collapse" data-parent="#navigation">Development Tools <b class="caret"></b></a><div id="navigation-1664" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-debug/blob/master/docs/guide/README.md">Debug Toolbar and Debugger</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md">Generating Code using Gii</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-apidoc">Generating API Documentation</a></div>
<a class="list-group-item" href="#navigation-1665" data-toggle="collapse" data-parent="#navigation">Testing <b class="caret"></b></a><div id="navigation-1665" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-test-overview.html">Overview</a>
<a class="list-group-item" href="./guide-test-environment-setup.html">Testing environment setup</a>
<a class="list-group-item" href="./guide-test-unit.html">Unit Tests</a>
<a class="list-group-item" href="./guide-test-functional.html">Functional Tests</a>
<a class="list-group-item" href="./guide-test-acceptance.html">Acceptance Tests</a>
<a class="list-group-item" href="./guide-test-fixtures.html">Fixtures</a></div>
<a class="list-group-item" href="#navigation-1666" data-toggle="collapse" data-parent="#navigation">Special Topics <b class="caret"></b></a><div id="navigation-1666" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md">Advanced Project Template</a>
<a class="list-group-item" href="./guide-tutorial-start-from-scratch.html">Building Application from Scratch</a>
<a class="list-group-item" href="./guide-tutorial-console.html">Console Commands</a>
<a class="list-group-item" href="./guide-tutorial-core-validators.html">Core Validators</a>
<a class="list-group-item" href="./guide-tutorial-i18n.html">Internationalization</a>
<a class="list-group-item" href="./guide-tutorial-mailing.html">Mailing</a>
<a class="list-group-item" href="./guide-tutorial-performance-tuning.html">Performance Tuning</a>
<a class="list-group-item" href="./guide-tutorial-shared-hosting.html">Shared Hosting Environment</a>
<a class="list-group-item" href="./guide-tutorial-template-engines.html">Template Engines</a>
<a class="list-group-item" href="./guide-tutorial-yii-integration.html">Working with Third-Party Code</a></div>
<a class="list-group-item" href="#navigation-1667" data-toggle="collapse" data-parent="#navigation">Widgets <b class="caret"></b></a><div id="navigation-1667" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-bootstrap/blob/master/docs/guide/README.md">Bootstrap Widgets</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-jui/blob/master/docs/guide/README.md">jQuery UI Widgets</a></div>
<a class="list-group-item" href="#navigation-1668" data-toggle="collapse" data-parent="#navigation">Helpers <b class="caret"></b></a><div id="navigation-1668" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-helper-overview.html">Overview</a>
<a class="list-group-item" href="./guide-helper-array.html">ArrayHelper</a>
<a class="list-group-item" href="./guide-helper-html.html">Html</a>
<a class="list-group-item" href="./guide-helper-url.html">Url</a></div></div>    </div>
    <div class="col-md-9 guide-content" role="main">
        <h1>Data Caching <span id="data-caching"></span><a href="#data-caching" class="hashlink">&para;</a></h1>
<div class="toc"><ol><li><a href="#cache-components">Cache Components</a></li>
<li><a href="#cache-apis">Cache APIs</a></li>
<li><a href="#query-caching">Query Caching</a></li></ol></div>
<p>Data caching is about storing some PHP variables in cache and retrieving it later from cache.
It is also the foundation for more advanced caching features, such as <a href="#query-caching">query caching</a>
and <a href="guide-caching-page.html">page caching</a>.</p>
<p>The following code is a typical usage pattern of data caching, where <code>$cache</code> refers to
a <a href="#cache-components">cache component</a>:</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">// try retrieving $data from cache</span>
<span class="hljs-variable">$data</span> = <span class="hljs-variable">$cache</span>-&gt;get(<span class="hljs-variable">$key</span>);

<span class="hljs-keyword">if</span> (<span class="hljs-variable">$data</span> === <span class="hljs-keyword">false</span>) {

    <span class="hljs-comment">// $data is not found in cache, calculate it from scratch</span>

    <span class="hljs-comment">// store $data in cache so that it can be retrieved next time</span>
    <span class="hljs-variable">$cache</span>-&gt;set(<span class="hljs-variable">$key</span>, <span class="hljs-variable">$data</span>);
}

<span class="hljs-comment">// $data is available here</span>
</code></pre>
<h2>Cache Components  <span id="cache-components"></span><a href="#cache-components" class="hashlink">&para;</a></h2><p>Data caching relies on the so-called <em>cache components</em> which represent various cache storage,
such as memory, files, databases.</p>
<p>Cache components are usually registered as <a href="guide-structure-application-components.html">application components</a> so
that they can be globally configurable
and accessible. The following code shows how to configure the <code>cache</code> application component to use
<a href="http://memcached.org/">memcached</a> with two cache servers:</p>
<pre><code class="hljs php language-php"><span class="hljs-string">'components'</span> =&gt; [
    <span class="hljs-string">'cache'</span> =&gt; [
        <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\caching\MemCache'</span>,
        <span class="hljs-string">'servers'</span> =&gt; [
            [
                <span class="hljs-string">'host'</span> =&gt; <span class="hljs-string">'server1'</span>,
                <span class="hljs-string">'port'</span> =&gt; <span class="hljs-number">11211</span>,
                <span class="hljs-string">'weight'</span> =&gt; <span class="hljs-number">100</span>,
            ],
            [
                <span class="hljs-string">'host'</span> =&gt; <span class="hljs-string">'server2'</span>,
                <span class="hljs-string">'port'</span> =&gt; <span class="hljs-number">11211</span>,
                <span class="hljs-string">'weight'</span> =&gt; <span class="hljs-number">50</span>,
            ],
        ],
    ],
],
</code></pre>
<p>You can then access the above cache component using the expression <code>Yii::$app-&gt;cache</code>.</p>
<p>Because all cache components support the same set of APIs, you can swap the underlying cache component
with a different one by reconfiguring it in the application configuration without modifying the code that uses the cache.
For example, you can modify the above configuration to use <a href="./yii-caching-apccache.html">APC cache</a>:</p>
<pre><code class="hljs php language-php"><span class="hljs-string">'components'</span> =&gt; [
    <span class="hljs-string">'cache'</span> =&gt; [
        <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\caching\ApcCache'</span>,
    ],
],
</code></pre>
<blockquote class="tip"><p><strong>Tip: </strong>You can register multiple cache application components. The component named <code>cache</code> is used
  by default by many cache-dependent classes (e.g. <a href="./yii-web-urlmanager.html">yii\web\UrlManager</a>).</p>
</blockquote>
<h3>Supported Cache Storage  <span id="supported-cache-storage"></span><a href="#supported-cache-storage" class="hashlink">&para;</a></h3><p>Yii supports a wide range of cache storage. The following is a summary:</p>
<ul>
<li><a href="./yii-caching-apccache.html">yii\caching\ApcCache</a>: uses PHP <a href="http://php.net/manual/en/book.apc.php">APC</a> extension. This option can be
considered as the fastest one when dealing with cache for a centralized thick application (e.g. one
server, no dedicated load balancers, etc.).</li>
<li><a href="./yii-caching-dbcache.html">yii\caching\DbCache</a>: uses a database table to store cached data. To use this cache, you must
create a table as specified in <a href="./yii-caching-dbcache.html#$cacheTable-detail">yii\caching\DbCache::$cacheTable</a>.</li>
<li><a href="./yii-caching-dummycache.html">yii\caching\DummyCache</a>: serves as a cache placeholder which does no real caching.
The purpose of this component is to simplify the code that needs to check the availability of cache.
For example, during development or if the server doesn't have actual cache support, you may configure
a cache component to use this cache. When an actual cache support is enabled, you can switch to use
the corresponding cache component. In both cases, you may use the same code
<code>Yii::$app-&gt;cache-&gt;get($key)</code> to attempt retrieving data from the cache without worrying that
<code>Yii::$app-&gt;cache</code> might be <code>null</code>.</li>
<li><a href="./yii-caching-filecache.html">yii\caching\FileCache</a>: uses standard files to store cached data. This is particular suitable
to cache large chunk of data, such as page content.</li>
<li><a href="./yii-caching-memcache.html">yii\caching\MemCache</a>: uses PHP <a href="http://php.net/manual/en/book.memcache.php">memcache</a>
and <a href="http://php.net/manual/en/book.memcached.php">memcached</a> extensions. This option can be considered as
the fastest one when dealing with cache in a distributed applications (e.g. with several servers, load
balancers, etc.)</li>
<li><a href="./yii-redis-cache.html">yii\redis\Cache</a>: implements a cache component based on <a href="http://redis.io/">Redis</a> key-value store
(redis version 2.6.12 or higher is required).</li>
<li><a href="./yii-caching-wincache.html">yii\caching\WinCache</a>: uses PHP <a href="http://iis.net/downloads/microsoft/wincache-extension">WinCache</a>
(<a href="http://php.net/manual/en/book.wincache.php">see also</a>) extension.</li>
<li><a href="./yii-caching-xcache.html">yii\caching\XCache</a>: uses PHP <a href="http://xcache.lighttpd.net/">XCache</a> extension.</li>
<li><p><a href="http://files.zend.com/help/Zend-Server-6/zend-server.htm#data_cache_component.htm">Zend Data Cache</a>
as the underlying caching medium.</p>
</li>
</ul>
<blockquote class="tip"><p><strong>Tip: </strong>You may use different cache storage in the same application. A common strategy is to use memory-based
  cache storage to store data that is small but constantly used (e.g. statistical data), and use file-based
  or database-based cache storage to store data that is big and less frequently used (e.g. page content).</p>
</blockquote>
<h2>Cache APIs  <span id="cache-apis"></span><a href="#cache-apis" class="hashlink">&para;</a></h2><p>All cache components have the same base class <a href="./yii-caching-cache.html">yii\caching\Cache</a> and thus support the following APIs:</p>
<ul>
<li><a href="./yii-caching-cache.html#get()-detail">get()</a>: retrieves a data item from cache with a specified key. A <code>false</code>
value will be returned if the data item is not found in the cache or is expired/invalidated.</li>
<li><a href="./yii-caching-cache.html#set()-detail">set()</a>: stores a data item identified by a key in cache.</li>
<li><a href="./yii-caching-cache.html#add()-detail">add()</a>: stores a data item identified by a key in cache if the key is not found in the cache.</li>
<li><a href="./yii-caching-cache.html#multiGet()-detail">multiGet()</a>: retrieves multiple data items from cache with the specified keys.</li>
<li><a href="./yii-caching-cache.html#multiSet()-detail">multiSet()</a>: stores multiple data items in cache. Each item is identified by a key.</li>
<li><a href="./yii-caching-cache.html#multiAdd()-detail">multiAdd()</a>: stores multiple data items in cache. Each item is identified by a key.
If a key already exists in the cache, the data item will be skipped.</li>
<li><a href="./yii-caching-cache.html#exists()-detail">exists()</a>: returns a value indicating whether the specified key is found in the cache.</li>
<li><a href="./yii-caching-cache.html#delete()-detail">delete()</a>: removes a data item identified by a key from the cache.</li>
<li><a href="./yii-caching-cache.html#flush()-detail">flush()</a>: removes all data items from the cache.</li>
</ul>
<blockquote class="note"><p><strong>Note: </strong>Do not cache a <code>false</code> boolean value directly because the <a href="./yii-caching-cache.html#get()-detail">get()</a> method uses
<code>false</code> return value to indicate the data item is not found in the cache. You may put <code>false</code> in an array and cache
this array instead to avoid this problem.</p>
</blockquote>
<p>Some cache storage, such as MemCache, APC, support retrieving multiple cached values in a batch mode,
which may reduce the overhead involved in retrieving cached data. The APIs <a href="./yii-caching-cache.html#multiGet()-detail">multiGet()</a>
and <a href="./yii-caching-cache.html#multiAdd()-detail">multiAdd()</a> are provided to exploit this feature. In case the underlying cache storage
does not support this feature, it will be simulated.</p>
<p>Because <a href="./yii-caching-cache.html">yii\caching\Cache</a> implements <code>ArrayAccess</code>, a cache component can be used like an array. The following
are some examples:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$cache</span>[<span class="hljs-string">'var1'</span>] = <span class="hljs-variable">$value1</span>;  <span class="hljs-comment">// equivalent to: $cache-&gt;set('var1', $value1);</span>
<span class="hljs-variable">$value2</span> = <span class="hljs-variable">$cache</span>[<span class="hljs-string">'var2'</span>];  <span class="hljs-comment">// equivalent to: $value2 = $cache-&gt;get('var2');</span>
</code></pre>
<h3>Cache Keys  <span id="cache-keys"></span><a href="#cache-keys" class="hashlink">&para;</a></h3><p>Each data item stored in cache is uniquely identified by a key. When you store a data item in cache,
you have to specify a key for it. Later when you retrieve the data item from cache, you should provide
the corresponding key.</p>
<p>You may use a string or an arbitrary value as a cache key. When a key is not a string, it will be automatically
serialized into a string.</p>
<p>A common strategy of defining a cache key is to include all determining factors in terms of an array.
For example, <a href="./yii-db-schema.html">yii\db\Schema</a> uses the following key to cache schema information about a database table:</p>
<pre><code class="hljs php language-php">[
    <span class="hljs-keyword">__CLASS__</span>,              <span class="hljs-comment">// schema class name</span>
    <span class="hljs-variable">$this</span>-&gt;db-&gt;dsn,         <span class="hljs-comment">// DB connection data source name</span>
    <span class="hljs-variable">$this</span>-&gt;db-&gt;username,    <span class="hljs-comment">// DB connection login user</span>
    <span class="hljs-variable">$name</span>,                  <span class="hljs-comment">// table name</span>
];
</code></pre>
<p>As you can see, the key includes all necessary information needed to uniquely specify a database table.</p>
<p>When the same cache storage is used by different applications, you should specify a unique cache key prefix
for each application to avoid conflicts of cache keys. This can be done by configuring the <a href="./yii-caching-cache.html#$keyPrefix-detail">yii\caching\Cache::$keyPrefix</a>
property. For example, in the application configuration you can write the following code:</p>
<pre><code class="hljs php language-php"><span class="hljs-string">'components'</span> =&gt; [
    <span class="hljs-string">'cache'</span> =&gt; [
        <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\caching\ApcCache'</span>,
        <span class="hljs-string">'keyPrefix'</span> =&gt; <span class="hljs-string">'myapp'</span>,       <span class="hljs-comment">// a unique cache key prefix</span>
    ],
],
</code></pre>
<p>To ensure interoperability, only alphanumeric characters should be used.</p>
<h3>Cache Expiration  <span id="cache-expiration"></span><a href="#cache-expiration" class="hashlink">&para;</a></h3><p>A data item stored in a cache will remain there forever unless it is removed because of some caching policy
enforcement (e.g. caching space is full and the oldest data are removed). To change this behavior, you can provide
an expiration parameter when calling <a href="./yii-caching-cache.html#set()-detail">set()</a> to store a data item. The parameter
indicates for how many seconds the data item can remain valid in the cache. When you call
<a href="./yii-caching-cache.html#get()-detail">get()</a> to retrieve the data item, if it has passed the expiration time, the method
will return <code>false</code>, indicating the data item is not found in the cache. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">// keep the data in cache for at most 45 seconds</span>
<span class="hljs-variable">$cache</span>-&gt;set(<span class="hljs-variable">$key</span>, <span class="hljs-variable">$data</span>, <span class="hljs-number">45</span>);

sleep(<span class="hljs-number">50</span>);

<span class="hljs-variable">$data</span> = <span class="hljs-variable">$cache</span>-&gt;get(<span class="hljs-variable">$key</span>);
<span class="hljs-keyword">if</span> (<span class="hljs-variable">$data</span> === <span class="hljs-keyword">false</span>) {
    <span class="hljs-comment">// $data is expired or is not found in the cache</span>
}
</code></pre>
<h3>Cache Dependencies  <span id="cache-dependencies"></span><a href="#cache-dependencies" class="hashlink">&para;</a></h3><p>Besides expiration setting, cached data item may also be invalidated by changes of the so-called <em>cache dependencies</em>.
For example, <a href="./yii-caching-filedependency.html">yii\caching\FileDependency</a> represents the dependency of a file's modification time.
When this dependency changes, it means the corresponding file is modified. As a result, any outdated
file content found in the cache should be invalidated and the <a href="./yii-caching-cache.html#get()-detail">get()</a> call
should return <code>false</code>.</p>
<p>Cache dependencies are represented as objects of <a href="./yii-caching-dependency.html">yii\caching\Dependency</a> descendant classes. When you call
<a href="./yii-caching-cache.html#set()-detail">set()</a> to store a data item in the cache, you can pass along an associated cache
dependency object. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">// Create a dependency on the modification time of file example.txt.</span>
<span class="hljs-variable">$dependency</span> = <span class="hljs-keyword">new</span> \yii\caching\FileDependency([<span class="hljs-string">'fileName'</span> =&gt; <span class="hljs-string">'example.txt'</span>]);

<span class="hljs-comment">// The data will expire in 30 seconds.</span>
<span class="hljs-comment">// It may also be invalidated earlier if example.txt is modified.</span>
<span class="hljs-variable">$cache</span>-&gt;set(<span class="hljs-variable">$key</span>, <span class="hljs-variable">$data</span>, <span class="hljs-number">30</span>, <span class="hljs-variable">$dependency</span>);

<span class="hljs-comment">// The cache will check if the data has expired.</span>
<span class="hljs-comment">// It will also check if the associated dependency was changed.</span>
<span class="hljs-comment">// It will return false if any of these conditions is met.</span>
<span class="hljs-variable">$data</span> = <span class="hljs-variable">$cache</span>-&gt;get(<span class="hljs-variable">$key</span>);
</code></pre>
<p>Below is a summary of the available cache dependencies:</p>
<ul>
<li><a href="./yii-caching-chaineddependency.html">yii\caching\ChainedDependency</a>: the dependency is changed if any of the dependencies on the chain is changed.</li>
<li><a href="./yii-caching-dbdependency.html">yii\caching\DbDependency</a>: the dependency is changed if the query result of the specified SQL statement is changed.</li>
<li><a href="./yii-caching-expressiondependency.html">yii\caching\ExpressionDependency</a>: the dependency is changed if the result of the specified PHP expression is changed.</li>
<li><a href="./yii-caching-filedependency.html">yii\caching\FileDependency</a>: the dependency is changed if the file's last modification time is changed.</li>
<li><a href="./yii-caching-tagdependency.html">yii\caching\TagDependency</a>: associates a cached data item with one or multiple tags. You may invalidate
the cached data items with the specified tag(s) by calling <a href="./yii-caching-tagdependency.html#invalidate()-detail">yii\caching\TagDependency::invalidate()</a>.</li>
</ul>
<blockquote class="note"><p><strong>Note: </strong>Avoid using <a href="./yii-caching-cache.html#exists()-detail">exists()</a> method along with dependencies. It does not check whether
  the dependency associated with the cached data, if there is any, has changed. So a call to
  <a href="./yii-caching-cache.html#get()-detail">get()</a> may return <code>false</code> while <a href="./yii-caching-cache.html#exists()-detail">exists()</a> returns <code>true</code>.</p>
</blockquote>
<h2>Query Caching  <span id="query-caching"></span><a href="#query-caching" class="hashlink">&para;</a></h2><p>Query caching is a special caching feature built on top of data caching. It is provided to cache the result
of database queries.</p>
<p>Query caching requires a <a href="./yii-db-connection.html">DB connection</a> and a valid <code>cache</code> <a href="#cache-components">application component</a>.
The basic usage of query caching is as follows, assuming <code>$db</code> is a <a href="./yii-db-connection.html">yii\db\Connection</a> instance:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$result</span> = <span class="hljs-variable">$db</span>-&gt;cache(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$db</span>)</span> </span>{

    <span class="hljs-comment">// the result of the SQL query will be served from the cache</span>
    <span class="hljs-comment">// if query caching is enabled and the query result is found in the cache</span>
    <span class="hljs-keyword">return</span> <span class="hljs-variable">$db</span>-&gt;createCommand(<span class="hljs-string">'SELECT * FROM customer WHERE id=1'</span>)-&gt;queryOne();

});
</code></pre>
<p>Query caching can be used for <a href="guide-db-dao.html">DAO</a> as well as <a href="guide-db-active-record.html">ActiveRecord</a>:</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$result</span> = Customer::getDb()-&gt;cache(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$db</span>)</span> </span>{
    <span class="hljs-keyword">return</span> Customer::find()-&gt;where([<span class="hljs-string">'id'</span> =&gt; <span class="hljs-number">1</span>])-&gt;one();
});
</code></pre>
<blockquote class="info"><p><strong>Info: </strong>Some DBMS (e.g. <a href="http://dev.mysql.com/doc/refman/5.1/en/query-cache.html">MySQL</a>)
  also support query caching on the DB server side. You may choose to use either query caching mechanism.
  The query caching described above has the advantage that you may specify flexible cache dependencies
  and are potentially more efficient.</p>
</blockquote>
<h3>Cache Flushing <span id="cache-flushing"> <span id="cache-flushing"></span><a href="#cache-flushing" class="hashlink">&para;</a></h3><p>When you need to invalidate all the stored cache data, you can call <a href="./yii-caching-cache.html#flush()-detail">yii\caching\Cache::flush()</a>.</p>
<p>You can flush the cache from the console by calling <code>yii cache/flush</code> as well.</p>
<ul>
<li><code>yii cache</code>: lists the available caches in application</li>
<li><code>yii cache/flush cache1 cache2</code>: flushes the cache components <code>cache1</code>, <code>cache2</code> (you can pass multiple component
 names separated with space)</li>
<li><code>yii cache/flush-all</code>: flushes all cache components in the application</li>
</ul>
<blockquote class="info"><p><strong>Info: </strong>Console application uses a separate configuration file by default. Ensure, that you have the same caching
components in your web and console application configs to reach the proper effect.</p>
</blockquote>
<h3>Configurations  <span id="query-caching-configs"></span><a href="#query-caching-configs" class="hashlink">&para;</a></h3><p>Query caching has three global configurable options through <a href="./yii-db-connection.html">yii\db\Connection</a>:</p>
<ul>
<li><a href="./yii-db-connection.html#$enableQueryCache-detail">enableQueryCache</a>: whether to turn on or off query caching.
It defaults to true. Note that to effectively turn on query caching, you also need to have a valid
cache, as specified by <a href="./yii-db-connection.html#$queryCache-detail">queryCache</a>.</li>
<li><a href="./yii-db-connection.html#$queryCacheDuration-detail">queryCacheDuration</a>: this represents the number of seconds
that a query result can remain valid in the cache. You can use 0 to indicate a query result should
remain in the cache forever. This property is the default value used when <a href="./yii-db-connection.html#cache()-detail">yii\db\Connection::cache()</a>
is called without specifying a duration.</li>
<li><a href="./yii-db-connection.html#$queryCache-detail">queryCache</a>: this represents the ID of the cache application component.
It defaults to <code>'cache'</code>. Query caching is enabled only if there is a valid cache application component.</li>
</ul>
<h3>Usages  <span id="query-caching-usages"></span><a href="#query-caching-usages" class="hashlink">&para;</a></h3><p>You can use <a href="./yii-db-connection.html#cache()-detail">yii\db\Connection::cache()</a> if you have multiple SQL queries that need to take advantage of
query caching. The usage is as follows,</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$duration</span> = <span class="hljs-number">60</span>;     <span class="hljs-comment">// cache query results for 60 seconds.</span>
<span class="hljs-variable">$dependency</span> = ...;  <span class="hljs-comment">// optional dependency</span>

<span class="hljs-variable">$result</span> = <span class="hljs-variable">$db</span>-&gt;cache(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$db</span>)</span> </span>{

    <span class="hljs-comment">// ... perform SQL queries here ...</span>

    <span class="hljs-keyword">return</span> <span class="hljs-variable">$result</span>;

}, <span class="hljs-variable">$duration</span>, <span class="hljs-variable">$dependency</span>);
</code></pre>
<p>Any SQL queries in the anonymous function will be cached for the specified duration with the specified dependency.
If the result of a query is found valid in the cache, the query will be skipped and the result will be served
from the cache instead. If you do not specify the <code>$duration</code> parameter, the value of
<a href="./yii-db-connection.html#$queryCacheDuration-detail">queryCacheDuration</a> will be used instead.</p>
<p>Sometimes within <code>cache()</code>, you may want to disable query caching for some particular queries. You can use
<a href="./yii-db-connection.html#noCache()-detail">yii\db\Connection::noCache()</a> in this case.</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$result</span> = <span class="hljs-variable">$db</span>-&gt;cache(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$db</span>)</span> </span>{

    <span class="hljs-comment">// SQL queries that use query caching</span>

    <span class="hljs-variable">$db</span>-&gt;noCache(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$db</span>)</span> </span>{

        <span class="hljs-comment">// SQL queries that do not use query caching</span>

    });

    <span class="hljs-comment">// ...</span>

    <span class="hljs-keyword">return</span> <span class="hljs-variable">$result</span>;
});
</code></pre>
<p>If you just want to use query caching for a single query, you can call <a href="./yii-db-command.html#cache()-detail">yii\db\Command::cache()</a> when building
the command. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">// use query caching and set query cache duration to be 60 seconds</span>
<span class="hljs-variable">$customer</span> = <span class="hljs-variable">$db</span>-&gt;createCommand(<span class="hljs-string">'SELECT * FROM customer WHERE id=1'</span>)-&gt;cache(<span class="hljs-number">60</span>)-&gt;queryOne();
</code></pre>
<p>You can also use <a href="./yii-db-command.html#noCache()-detail">yii\db\Command::noCache()</a> to disable query caching for a single command. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$result</span> = <span class="hljs-variable">$db</span>-&gt;cache(<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">(<span class="hljs-variable">$db</span>)</span> </span>{

    <span class="hljs-comment">// SQL queries that use query caching</span>

    <span class="hljs-comment">// do not use query caching for this command</span>
    <span class="hljs-variable">$customer</span> = <span class="hljs-variable">$db</span>-&gt;createCommand(<span class="hljs-string">'SELECT * FROM customer WHERE id=1'</span>)-&gt;noCache()-&gt;queryOne();

    <span class="hljs-comment">// ...</span>

    <span class="hljs-keyword">return</span> <span class="hljs-variable">$result</span>;
});
</code></pre>
<h3>Limitations  <span id="query-caching-limitations"></span><a href="#query-caching-limitations" class="hashlink">&para;</a></h3><p>Query caching does not work with query results that contain resource handlers. For example,
when using the <code>BLOB</code> column type in some DBMS, the query result will return a resource
handler for the column data.</p>
<p>Some caching storage has size limitation. For example, memcache limits the maximum size
of each entry to be 1MB. Therefore, if the size of a query result exceeds this limit,
the caching will fail.</p>
        <div class="toplink"><a href="#" class="h1" title="go to top"><span class="glyphicon glyphicon-arrow-up"></a></div>
    </div>
</div>


</div>

<footer class="footer">
        <p class="pull-right"><small>Page generated on Sat, 09 Jul 2016 12:16:31 +0000</small></p>
    Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a></footer>

<script type="text/javascript">jQuery(document).ready(function () {
    var shiftWindow = function () { scrollBy(0, -50) };
    if (location.hash) setTimeout(shiftWindow, 1);
    window.addEventListener("hashchange", shiftWindow);
var element = document.createElement("script");
element.src = "./jssearch.index.js";
document.body.appendChild(element);

var searchBox = $('#searchbox');

// search when typing in search field
searchBox.on("keyup", function(event) {
    var query = $(this).val();

    if (query == '' || event.which == 27) {
        $('#search-resultbox').hide();
        return;
    } else if (event.which == 13) {
        var selectedLink = $('#search-resultbox a.selected');
        if (selectedLink.length != 0) {
            document.location = selectedLink.attr('href');
            return;
        }
    } else if (event.which == 38 || event.which == 40) {
        $('#search-resultbox').show();

        var selected = $('#search-resultbox a.selected');
        if (selected.length == 0) {
            $('#search-results').find('a').first().addClass('selected');
        } else {
            var next;
            if (event.which == 40) {
                next = selected.parent().next().find('a').first();
            } else {
                next = selected.parent().prev().find('a').first();
            }
            if (next.length != 0) {
                var resultbox = $('#search-results');
                var position = next.position();

//              TODO scrolling is buggy and jumps around
//                resultbox.scrollTop(Math.floor(position.top));
//                console.log(position.top);

                selected.removeClass('selected');
                next.addClass('selected');
            }
        }

        return;
    }
    $('#search-resultbox').show();
    $('#search-results').html('<li><span class="no-results">No results</span></li>');

    var result = jssearch.search(query);

    if (result.length > 0) {
        var i = 0;
        var resHtml = '';

        for (var key in result) {
            if (i++ > 20) {
                break;
            }
            resHtml = resHtml +
            '<li><a href="' + result[key].file.u.substr(3) +'"><span class="title">' + result[key].file.t + '</span>' +
            '<span class="description">' + result[key].file.d + '</span></a></li>';
        }
        $('#search-results').html(resHtml);
    }
});

// hide the search results on ESC
$(document).on("keyup", function(event) { if (event.which == 27) { $('#search-resultbox').hide(); } });
// hide search results on click to document
$(document).bind('click', function (e) { $('#search-resultbox').hide(); });
// except the following:
searchBox.bind('click', function(e) { e.stopPropagation(); });
$('#search-resultbox').bind('click', function(e) { e.stopPropagation(); });

});</script></body>
</html>
